package com.ruizhong.centercontroll.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

public class    HTTPSender {
    public static String sendWithGET(String aimIpAddress, Integer aimPort, byte[] message, String requestPath, Boolean needReply) {
        try {
            String[] split = requestPath.split("/");
            StringBuilder encodeRequestPath = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                String s = split[i];
                if (StringUtils.isEmpty(s)){
                    continue;
                }
                encodeRequestPath.append("/"+URLEncoder.encode(s, "utf8"));
            }

            URL url = new URL("http://" + aimIpAddress + ":" + aimPort + encodeRequestPath.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 发送请求并获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印结果
            System.out.println(response.toString());
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sendWithPOST(String ipAddress, int port, byte[] instructionData, String requestPath, boolean needReply) {
        try {
            String[] split = requestPath.split("/");
            StringBuilder encodeRequestPath = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                String s = split[i];
                if (StringUtils.isEmpty(s)){
                    continue;
                }
                encodeRequestPath.append("/"+URLEncoder.encode(s, "utf8"));
            }
            // 创建URL对象，指向你想要发送POST请求的地址
            URL url = new URL("http://" + ipAddress + ":" + port + encodeRequestPath);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头（如果需要的话）
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");

            // 允许输出（发送请求体）
            connection.setDoOutput(true);



            // 写入请求体数据（这里以JSON格式为例）
            if (!StringUtils.isEmpty(instructionData)){
                // 获取输出流，用于写入请求体
                OutputStream os = connection.getOutputStream();
                String input = new String( instructionData);
                if (!validateJson(input)) {


                    // 1. 提取键值对
                    input = input.replaceAll("[{}]", ""); // 移除大括号
                    String[] pairs = input.split(",\\s*");

                    // 2. 构建Map
                    Map<String, Object> map = new HashMap<>();
                    for (String pair : pairs) {
                        String[] keyValue = pair.split("=");
                        String key = keyValue[0].trim();
                        String value = keyValue[1].trim();
                        map.put(key, value);
                    }

                    // 3. 转换为标准JSON
                    JSONObject json = new JSONObject(map);
                    input= json.toString();

                }
                os.write(input.getBytes("utf-8"));
                os.flush();
                // 关闭输出流
                os.close();
            }


            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            // 处理响应（如果需要的话）
            // ...
// 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印结果
            System.out.println(response.toString());
            // 关闭连接
            connection.disconnect();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    // 综合JSON校验方法
    private static Boolean validateJson(String json) throws IllegalArgumentException {
        if (StringUtils.isEmpty(json)) {
            return false;
        }

        String trimmed = json.trim();
        if (trimmed.isEmpty()) {
            return false;
        }

        // 基本结构检查
        if (!(trimmed.startsWith("{") && trimmed.endsWith("}")) &&
                !(trimmed.startsWith("[") && trimmed.endsWith("]"))) {
            return false;
        }

        // 使用Jackson进行严格校验
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.readTree(trimmed);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    public static String sendWithPUT(String ipAddress, int port, byte[] instructionData, String requestPath, boolean needReply) {
        try {
            String[] split = requestPath.split("/");
            StringBuilder encodeRequestPath = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                String s = split[i];
                if (StringUtils.isEmpty(s)){
                    continue;
                }
                encodeRequestPath.append("/"+URLEncoder.encode(s, "utf8"));
            }
            // 创建URL对象，指向你想要发送PUT请求的地址
            URL url = new URL("http://" + ipAddress + ":" + port + encodeRequestPath);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为PUT
            connection.setRequestMethod("PUT");

            // 设置请求头（如果需要的话）
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");

            // 允许输出（发送请求体）
            connection.setDoOutput(true);

            // 如果需要，可以设置请求体为“无内容”的PUT请求（即不发送任何数据）
            // 但通常PUT请求会包含一些要更新的数据

            // 获取输出流，用于写入请求体
            OutputStream os = connection.getOutputStream();

            // 写入请求体数据（这里以JSON格式为例）
            String jsonInputString = new String(instructionData);
            os.write(jsonInputString.getBytes("utf-8"));
            os.flush();

            // 关闭输出流
            os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            // 处理响应（如果需要的话）
            // 例如，读取响应体并解析JSON数据
            // ...
// 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印结果
            System.out.println(response.toString());

            // 关闭连接
            connection.disconnect();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sendWithDELETE(String ipAddress, int port, byte[] instructionData, String requestPath, boolean needReply) {
        try {
            String[] split = requestPath.split("/");
            StringBuilder encodeRequestPath = new StringBuilder();
            for (int i = 0; i < split.length; i++) {
                String s = split[i];
                if (StringUtils.isEmpty(s)){
                    continue;
                }
                encodeRequestPath.append("/"+URLEncoder.encode(s, "utf8"));
            }
            // 创建URL对象，指向你想要发送DELETE请求的地址
            URL url = new URL("http://" + ipAddress + ":" + port + encodeRequestPath);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为DELETE
            connection.setRequestMethod("DELETE");

            // 设置请求头（如果需要的话）
            // 例如，设置Accept头部来告诉服务器你期望接收的数据类型
            connection.setRequestProperty("Accept", "application/json");

            // 由于DELETE请求通常不包含请求体，所以不需要设置setDoOutput(true)

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);
            String reply = null;
            // 处理响应（如果需要的话）
            // 例如，读取响应体并解析JSON数据（如果服务器返回了JSON）
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
                // 通常，DELETE请求成功时，服务器会返回200 OK（尽管这不是RESTful的最佳实践）
                // 或者204 No Content，表示请求成功但没有内容返回
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印响应体（如果有的话）
                System.out.println("Response: " + response.toString());
                reply = response.toString();
            } else {
                // 处理错误响应
                // 例如，读取错误流并打印错误信息
                BufferedReader errorStream = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                String errorMessage;
                StringBuilder errorResponse = new StringBuilder();

                while ((errorMessage = errorStream.readLine()) != null) {
                    errorResponse.append(errorMessage);
                }
                errorStream.close();

                System.err.println("Error Response: " + errorResponse.toString());
                reply = errorResponse.toString();
            }

            // 关闭连接
            connection.disconnect();
            return reply;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}